# 对摄影作品的发布、删除、查看、搜索

from flask import Blueprint, request
from libs.response import generate_response
from flask_restful import Resource, Api
from sqlalchemy import or_
import os
import time
from model.photo import Photo
from model import db
from libs.auth import login

photoapi_bp = Blueprint("photoapi", __name__, url_prefix='/v1')
api = Api(photoapi_bp)


class PhotoView(Resource):
    # @login
    # 测试成功
    def post(self):
        data = request.form
        img = request.files.get("photo_path")  # 从表单中获取图片数据
        suffix = '.' + img.filename.split('.')[-1]  # 获取文件后缀名
        basedir = "D:\\2022newproject\\VBProject"  # os.path.abspath(os.path.dirname(__file__))  # 获取当前文件路径
        photo = '/static/uploads/' + str(int(time.time())) + suffix  # 拼接相对路径
        photo_path = basedir + photo  # 拼接图片完整保存路径,时间戳命名文件防止重复
        img.save(photo_path)  # 保存图片
        print(photo_path)
        photo = Photo(
            photo_path=photo_path,
            photo_name=data.get("photo_name"),
            content=data.get("content"),
            category_id=data.get("category_id"),
            user_ip=data.get("user_ip")
        )
        db.session.add(photo)
        db.session.commit()
        return generate_response(message="成功发布一张照片！！")

    # 测试成功
    def delete(self, id):
        del_photo = Photo.query.get(id)
        # 能查询到id就删除，因为id是主键，唯一的
        if del_photo:
            db.session.delete(del_photo)
            db.session.commit()
            return generate_response(message="照片删掉啦~")
        else:
            return generate_response(status_code=10001, message="这张照片真的有吗？！！！")

        # 127.0.0.1:9000/v1/photo/4

    # 测试成功
    def get(self):
        photo_list = []
        keyword = request.args.get("keyword")
        # 支持照片名、内容、分类查询
        if keyword is not None:
            photos_info = Photo.query.filter(or_(Photo.photo_name.like('%'+keyword+'%'), Photo.content.like('%'+keyword+'%'), Photo.category_id.like('%'+keyword+'%'))).all()
            print(photos_info)  # [<UserManager 4>]
        else:
            photos_info = Photo.query.all()

        for photo in photos_info:
            photo.load_time = photo.load_time.strftime('%Y-%m-%d %H:%M:%S')
            photo.tags = [dict(i) for i in photo.tags]
        photo_list += photos_info
        return generate_response(message="get info success", data=[dict(photo) for photo in photo_list])


api.add_resource(PhotoView, '/photo')
api.add_resource(PhotoView, "/photo/<int:id>", endpoint="photoviewapi")
